<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" :disabled="isView" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="formData.customerId"
          clearable
          placeholder="请选择客户"
          :disabled="isView"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="第一次回访时间" prop="firstTime">
        <el-date-picker
          v-model="formData.firstTime"
          type="date"
          value-format="x"
          placeholder="选择第一次回访时间"
        />
      </el-form-item> -->
      <!-- <el-form-item label="第一次回访时间" prop="lastTime">
        <el-date-picker
          v-model="formData.lastTime"
          type="date"
          value-format="x"
          placeholder="选择第一次回访时间"
        />
      </el-form-item> -->
      <el-form-item label="负责人" prop="principal">
        <el-select
          v-model="formData.principal"
          clearable
          filterable
          placeholder="请输入负责人"
          :disabled="isView"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="!isView" @click="submitForm" type="primary" :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">{{ isView ? '关 闭' : '取 消' }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CustomerFollowUpPlanApi, CustomerFollowUpPlanVO } from '@/api/erp/customer/followupplan'
import { CustomerApi, CustomerVO } from '@/api/erp/customer/customer'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
/** ERP 客户回访计划 表单 */
defineOptions({ name: 'CustomerFollowUpPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；view - 查看
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserVO[]>([]) // 用户列表
const formData = ref({
  id: undefined,
  name: undefined,
  customerId: undefined,
  firstTime: undefined,
  lastTime: undefined,
  principal: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  principal: [{ required: true, message: '负责人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 计算属性：是否为查看模式 */
const isView = computed(() => formType.value === 'view')

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await CustomerFollowUpPlanApi.getCustomerFollowUpPlan(id)
      // 确保customerId和principal是数字类型，以便与select选项匹配
      formData.value = {
        ...data,
        customerId: data.customerId ? Number(data.customerId) : undefined,
        principal: data.principal ? Number(data.principal) : undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerFollowUpPlanVO
    if (formType.value === 'create') {
      await CustomerFollowUpPlanApi.createCustomerFollowUpPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerFollowUpPlanApi.updateCustomerFollowUpPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    customerId: undefined,
    firstTime: undefined,
    lastTime: undefined,
    principal: undefined
  }
  formRef.value?.resetFields()
}
/** 初始化 **/
onMounted(async () => {
  userList.value = await UserApi.getSimpleUserList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
})
</script>
